class SceneTitle extends GuaScene {
    constructor(game) {
        super(game)
        this.setup()
    }

    setup() {
        this.context = this.game.context
        this.level = levels[LEVEL[0]][LEVEL[1]]
        this.suns = []
        this.sunscore = []
        this.zombies = []
        this.peas = []
        this.shrooms = []
        this.flowers = []
        this.booms = []
        this.potatoMine = []
        this.hypnoshroom = []
        this.chomper = []
        this.iceshrooms = []
        this.spikeweeds = []
        this.garlics = []
        this.others = []
        this.plants = []
        this.bullets = []
        this.plantIcons = []
        this.plantCards = []
        this.plantCard = []
        this.pawnMower = []
        this.offsetX = 255
        this.offsetY = 100
        this.zombieoffsetY = 20
        this.widthOfColumn = 80
        this.heightOfRow = 100
        this.cooldown = 100
        this.zombiecooldown = 100
        this.numOfZombie = 0
        this.ZOM = [Zombie, BucketHeadZombie, ConeheadZombie, FlagZombie]
        this.width = 1100
        this.bulletHitOffset = config.hit_offset.value

        this.setupCards()
        this.setupLevel()
        this.setupBG()
        this.setupInputs()
        this.setupInputScore()
        this.setupZombies()
        // this.setupPlants()
        // this.setupPlantIcon()
        this.setupCardBack()
        this.setupPlantCard()
        this.setupScore()
        this.setupSun()
        this.setupLawnMower()
        this.draw()
        this.setupPrepare()
    }

    update() {
        super.update();

        // 开火和碰撞检测
        this.updateFire()
        this.updateBoom()
        this.updatePotatoMine()
        this.updateShroom()
        this.updateGarlic()
        this.updateSpikeweed()
        this.updateIceshroom()
        this.updatehypnoshroom()
        this.updateChomper()
        this.updateOther()
        this.updateHit()
        this.updateSceneSun()
        this.updateSun()
        this.updateZombie()
        this.updateLawnMower()
        this.updatePrepare()
        this.updateScene()

    }

    draw() {
        super.draw()
        this.setupScore()
        for (let p of this.plantCards) {
            if (!p.ready) {

                let h = Math.floor((p.cooldown) / 10)
                let y = Math.floor((p.cooldown) / 10) - h + 13
                this.context.fillStyle = 'rgba(200, 200, 200, 0.8)'
                this.context.fillRect(p.x, y, p.w, h)
                p.cooldown--
                if (p.cooldown === 0) {
                    p.ready = true
                    p.cooldown = 700
                }
            }

        }
    }

// setup 系列
    setupCards() {
        if (cards.length === 0) {
            // this.cards = ['card_Peashooter', 'card_PotatoMine', 'card_Gralic', 'card_TwinSunflower', 'card_wallnut',
            //     'card_cherrybomb'
            // ]

            this.cards = ['card_Peashooter', 'card_PotatoMine', 'card_Gralic', 'card_TwinSunflower', 'card_wallnut',
                'card_cherrybomb', 'card_chomper', 'card_hypnoshroom', 'card_iceshroom', 'card_jalapeno', 'card_repeaterpea',
                'card_snowpea', 'card_squash', 'card_sunflower', 'card_sunshroom', 'card_threepeashooter', 'card_PumpkinHead',
                'card_scaredyshroom', 'card_spikeweed'
            ]
        } else {
            this.cards = cards
        }
    }

    setupPrepare() {
        this.addSlogan('slogan_prepare')
        this.sloganlarge = this.slogancooldown[0]
        this.sloganfinal = 200
    }

    setupScore() {
        let context = this.game.context
        context.font = "25px Georgia"
        this.context.fillStyle = 'rgba(0, 0, 0, 1)'
        context.fillText(this.score, 210, 80)
    }

    setupLevel() {
        let self = this
        this.slogancooldown = this.level.splice(4)
        window.addEventListener('keydown', function (event) {
            let k = event.key
            if ('123456789'.includes(k)) {
                // game.scene.level = loadLevel(game, Number(k))
                self.level = loadLevel(Number(k))
                self.setupZombies()
            }
        })
    }

    setupBG() {
        let lbg = LEVEL[0]
        log('lbg', lbg)
        let back = getbg(lbg)
        let bg = GuaImage.new(this.game, back)
        this.addElement(bg)
    }

    setupPlants() {
        for (let j = 0; j < 1; j++) {
            for (let i = 0; i < 3; i++) {
                // 255 和 100 是横纵的 offset
                this.addInitPlant(i, j)
            }
        }
    }

    setupPlantIcon() {
        this.addPlantIcon('sunFlowericon', 120, 0)
        this.addPlantIcon('peashootericon', 120, 1)
        this.addPlantIcon('snowPeaicon', 120, 2)

        this.addPlantIcon('potatoMineicon', 120, 3)
        this.addPlantIcon('puffShroomicon', 120, 4)
    }

    setupPlantCard() {
        let y = 13
        for (let c of this.cards) {
            this.plantCard.push(c)
        }
        for (let i = 0; i < this.plantCard.length; i++) {
            this.addPlantCard(this.plantCard[i], i, y)
        }

    }


    setupZombies() {
        for (let z of this.zombies) {
            z.die()
        }
        this.zombies = []
        for (let i = 0; i < this.level.length; i++) {
            let l = this.level[i]
            log('l', l)
            for (let j = 0; j < l; j++) {
                this.addZombie(this.ZOM[i], j)
            }

        }
        this.numOfZombie = this.zombies.length - 1
    }

    setupSun() {
        let pb = Sun.new(this.game)
        this.sun = pb
    }

    setupCardBack() {
        let b1 = PlantCard.new(this.game, 'card_back')
        let b2 = PlantCard.new(this.game, 'sun_back')
        let b3 = PlantCard.new(this.game, 'sun')
        let b4 = PlantCard.new(this.game, 'score_back')
        let b5 = PlantCard.new(this.game, 'ShovelBack_card')
        let b6 = PlantCard.new(this.game, 'Shovel_card')
        b1.x = 200
        b2.x = 210
        b3.x = 220
        b3.y = 10
        b4.x = 208
        b4.y = 60
        b5.x = 805
        b5.y = 30
        b6.x = 805
        b6.y = 30
        b6.column = Math.floor(b6.x / 50)
        this.addElement(b1)
        this.addElement(b2)
        this.addElement(b3)
        this.addElement(b4)
        this.addElement(b5)
        this.addElement(b6)
        this.plantCards.push(b6)
    }

    setupLawnMower() {
        for (let i = 1; i < 6; i++) {
            let lm = LawnMower.new(this.game)
            lm.y = this.zombieoffsetY + i * this.heightOfRow
            lm.row = i - 1
            log('lm.y', lm.y)
            this.addElement(lm)
            this.pawnMower.push(lm)
        }

    }

    setupInputScore() {
        // mouse inputs
        let self = this
        this.game.registerMouse(function (event, status) {
            let x = event.offsetX
            let y = event.offsetY

            let r = Math.floor((y) / 50)
            let c = Math.floor((x) / 50)
            // log('Score', x, c, y, r)
            // pb.row = Math.floor(randomBetween(100, 400) / 50)
            // pb.column = Math.floor(randomBetween(250, 900) / 50)

            if (status == 'down') {
                for (let s of self.suns) {
                    // log('row column', s.row, s.column)
                    if (x > s.x && x < (s.x + 80)) {
                        // log('inx')
                        if (y > (s.y - 10) && y < (s.y + 80)) {
                            s.point = true
                            // log(s.point)
                            self.updateScore()
                        }
                    }
                }
            }
        })
    }

    setupInputs() {
        // mouse inputs
        let self = this
        let startDrag = false
        let ox = 0
        let oy = 0
        this.game.registerMouse(function (event, status) {
            let x = event.offsetX
            let y = event.offsetY
            let r = Math.floor(y / 50)
            let c = Math.floor(x / 50)

            for (let p of self.plantCards) {
                if (r <= 1 && p.column == c) {
                    self.plantIcon = p
                }
            }

            if (status == 'down') {
                if (self.plantIcon) {
                    log('self.plantIcon', self.plantIcon)
                    if (self.plantIcon.ready) {
                        let at = self.plantIcon.pointInFrame(x, y)
                        if (at) {
                            startDrag = true
                            self.icon = self.plantIcon.clone()
                            self.addElement(self.icon)
                            // 设置偏移的 x 和 y
                            ox = self.plantIcon.x - x
                            oy = self.plantIcon.y - y
                        }
                    }

                }
            } else if (status == 'move') {
                if (self.icon) {
                    self.icon.x = x + ox
                    self.icon.y = y + oy
                }

            } else {
                if (startDrag) {
                    if (self.plantIcon.name !== "Shovel_card") {
                        self.addPlant(self.icon.name, x, y)
                    } else {
                        self.shovelPlant(self.icon)
                    }
                    self.removeElement(self.icon)
                }
                startDrag = false
            }


        })

    }

    shovelPlant(shovel) {
        let column = Math.floor(shovel.x / this.widthOfColumn) - 1
        let row = Math.floor(shovel.y / this.heightOfRow) - 1
        // log('column row', column, row)
        for (let p of this.plants) {
            // log(p.row, p.column)
            if (p.row == row && p.column == column) {
                // log('shovel')
                p.remove()
            }
        }
    }

// add 系列
    addZombie(ZOMBIE, i) {
        // row 表示第几排，场景会自动计算坐标，所以不应该设置 zombie 的坐标
        let row = randomBetween(0, 4)
        let zombie = ZOMBIE.new(this.game)
        zombie.x = 1100 + i * 15
        zombie.y = this.zombieoffsetY + row * this.heightOfRow
        zombie.row = row
        zombie.column = Math.floor(zombie.x / this.widthOfColumn)
        this.addElement(zombie)
        this.zombies.push(zombie)
    }

    addHead(zombie) {
        // row 表示第几排，场景会自动计算坐标，所以不应该设置 zombie 的坐标
        zombie.head.x = zombie.x
        zombie.head.y = zombie.y
        this.addElement(zombie.head)
    }

    addInitPlant(row, column) {
        let p = PeaShooter.new(this.game)
        p.x = this.offsetX + column * this.widthOfColumn
        p.y = this.offsetY + row * this.heightOfRow
        p.row = row
        this.plants.push(p)
        this.peas.push(p)
        this.addElement(p)
    }

    creatPlant(p, plants, x, y) {
        if (this.score >= p.score) {
            let column = Math.floor(x / this.widthOfColumn)
            let row = Math.floor((y) / this.heightOfRow)

            p.row = row - 1
            p.column = column
            p.x = column * this.widthOfColumn
            p.y = row * this.heightOfRow
            log('Plant column row ', p.row)
            this.score -= p.score
            this.addElement(p)
            plants.push(p)
            this.plantIcon.ready = false
        }
    }

    addPlant(name, x, y) {

        // let p = this.getPlant(name)
        // log('name', name)
        log(this.plantCards)
        let p0 = getPeabyCard(name, this.game)
        let p1 = getShroombyCard(name, this.game)
        let p2 = getFlowerbyCard(name, this.game)
        let p3 = getBoombyCard(name, this.game)
        let p4 = getPotatoMinebyCard(name, this.game)
        let p5 = getHypnoshroombyCard(name, this.game)
        let p6 = getChomperbyCard(name, this.game)
        let p7 = getGarlicbyCard(name, this.game)
        let p8 = getSpikeweedbyCard(name, this.game)
        let p9 = getIceshroombyCard(name, this.game)
        let p = getOtherbyCard(name, this.game)


        if (p0) {
            this.creatPlant(p0, this.peas, x, y)
            this.plants.push(p0)
        } else if (p1) {
            this.creatPlant(p1, this.shrooms, x, y)
            this.plants.push(p1)
        } else if (p2) {
            this.creatPlant(p2, this.flowers, x, y)
            this.plants.push(p2)
        } else if (p3) {
            this.creatPlant(p3, this.booms, x, y)
            this.plants.push(p3)
        } else if (p4) {
            this.creatPlant(p4, this.potatoMine, x, y)
            this.plants.push(p4)
        } else if (p5) {
            this.creatPlant(p5, this.hypnoshroom, x, y)
            this.plants.push(p5)
        } else if (p6) {
            this.creatPlant(p6, this.chomper, x, y)
            this.plants.push(p6)
        } else if (p7) {
            this.creatPlant(p7, this.garlics, x, y)
            this.plants.push(p7)
        } else if (p8) {
            this.creatPlant(p8, this.spikeweeds, x, y)
            this.plants.push(p8)
        } else if (p9) {
            this.creatPlant(p9, this.iceshrooms, x, y)
            this.plants.push(p9)
        } else if (p) {
            this.creatPlant(p, this.others, x, y)
            this.plants.push(p)
        } else {
            log('没找到对应植物')
        }
    }

    addPlantIcon(name, x, row) {
        let p = PlantIcon.new(this.game, name)
        // this.plantIcon = p
        p.x = x
        p.y = 10 + row * 70
        this.addElement(p)
        this.plantIcons.push(p)
    }

    addPlantCard(name, column, y) {
        let p = PlantCard.new(this.game, name)
        p.x = 300 + column * 50
        p.y = y
        p.column = Math.floor(p.x / 50)
        this.addElement(p)
        this.plantCards.push(p)
    }

    addSlogan(name) {
        // log('name', name)
        let s = Slogan.new(this.game, name)

        this.addElement(s)
        this.slogan = s
    }

// remove 系列
    removeBullet(bullet) {
        this.bullets = this.bullets.filter(e => {
            return e != bullet
        })
        this.removeElement(bullet)
    }

    removePlant(plant) {
        this.plants = this.plants.filter(e => {
            return e != plant
        })
        this.removeElement(plant)
    }

    removeBoom(boom) {
        this.plants = this.plants.filter(e => {
            return e != boom
        })
        this.booms = this.booms.filter(e => {
            return e != boom
        })
        this.removeElement(boom)
    }

    removeChomper(chomp) {
        this.chomper = this.chomper.filter(e => {
            return e != chomp
        })
        this.removePlant(chomp)
    }

    removeGarlic(garlic) {
        this.garlics = this.garlics.filter(e => {
            return e != garlic
        })
        this.removePlant(garlic)
    }

    removeSpikeweed(spikeweed) {
        this.spikeweeds = this.spikeweeds.filter(e => {
            return e != spikeweed
        })
        this.removePlant(spikeweed)
    }

    removeIceshroom(iceshroom) {
        this.iceshrooms = this.iceshrooms.filter(e => {
            return e != iceshroom
        })
        this.removePlant(iceshroom)
    }

    removeShroom(shroom) {
        this.plants = this.plants.filter(e => {
            return e != shroom
        })
        this.shrooms = this.shrooms.filter(e => {
            return e != shroom
        })
        this.removeElement(shroom)
    }

    removeFlower(flower) {
        this.plants = this.plants.filter(e => {
            return e != flower
        })
        this.flowers = this.flowers.filter(e => {
            return e != flower
        })
        this.removeElement(flower)
    }

    removePotatoMine(potatoM) {
        this.plants = this.plants.filter(e => {
            return e != potatoM
        })
        this.potatoMine = this.potatoMine.filter(e => {
            return e != potatoM
        })
        log('potatoM', potatoM)
        this.removeElement(potatoM.mashed)
        this.removeElement(potatoM)
    }


    removeHypnoshroom(hypnos) {
        this.plants = this.plants.filter(e => {
            return e != hypnos
        })
        this.hypnoshroom = this.hypnoshroom.filter(e => {
            return e != hypnos
        })
        this.removeElement(hypnos)
    }

    removeOther(other) {
        this.plants = this.plants.filter(e => {
            return e != other
        })
        this.others = this.others.filter(e => {
            return e != other
        })
        this.removeElement(other)
    }


    removeZombie(zombie) {
        this.zombies = this.zombies.filter(z => {
            return z != zombie
        })
        this.removeElement(zombie)
    }

    removeHead(zombie) {

        this.removeElement(zombie.head)
    }

    removeSun(sun) {
        this.suns = this.suns.filter(e => {
            return e != sun
        })
        this.removeElement(sun)
    }

    removeLawnMower(lawnmower) {
        this.pawnMower = this.pawnMower.filter(e => {
            return e != lawnmower
        })
        this.removeElement(lawnmower)
    }

    removeSlogan(slogan) {
        this.removeElement(slogan)
    }

// update 系列
    updateSceneSun() {
        this.cooldown--
        if (this.cooldown == 0) {
            // 开始冷却
            this.cooldown = 100
            // 释放阳光
            let pb = Sun.new(this.game, animationsunflower)

            pb.row = Math.floor(randomBetween(100, 550) / 50)
            pb.column = Math.floor(randomBetween(250, 900) / 50)

            pb.x = pb.column * 50
            pb.y = -50
            pb.k = (pb.x - pb.gx) / pb.speed
            // log('x, y', pb.x, pb.column, pb.row * 50, pb.row)
            this.game.scene.addElement(pb)
            this.suns.push(pb)
        }
        for (let s of this.suns) {
            s.update()
        }

    }

    updateZombie() {
        this.zombiecooldown--
        if (this.zombiecooldown < 0) {
            this.zombiecooldown = 100
        } else if (this.zombiecooldown === 0) {
            if (this.numOfZombie <= 5 && this.numOfZombie > -1) {
                this.addSlogan('slogan_final')
                for (let i = 0; i <= this.numOfZombie; i++) {
                    this.zombies[i].ready = true
                }
                this.numOfZombie = -1

            } else if (this.numOfZombie > 5) {

                let num = randomBetween(1, 5)
                if (this.numOfZombie === 5) {
                    this.addSlogan('slogan_large')
                }
                for (let i = 0; i < num; i++) {
                    this.zombies[this.numOfZombie].ready = true
                    this.numOfZombie -= 1
                }


            } else {
                log('僵尸激活完毕')
            }

        }
    }

    updateSun() {
        // log('this.suns', this.suns)
        for (let sun of this.suns) {
            if (sun.point) {
                log('point')
                sun.collect()
                if (sun.recycle) {
                    sun.remove()
                }
            }
        }
    }


    updateBoom() {
        for (let p of this.booms) {
            for (let z of this.zombies) {
                if (p.boom) {
                    if (z.x > p.x && z.x < p.x + p.range && p.row === z.row && z.ready) {
                        z.boomdie()
                    }
                } else {
                    if (p.x < z.x && p.x > z.x - 10 && p.row === z.row && z.ready) {
                        p.attack()
                        z.attacking()
                    }
                }
            }
        }
    }

    updatePotatoMine() {
        for (let p of this.potatoMine) {
            for (let z of this.zombies) {
                if (p.ready) {
                    if (p.x < z.x && p.x > z.x - 10 && p.row === z.row && z.ready) {
                        p.booming()
                        z.boomdie()
                    }
                } else {
                    if (p.x < z.x && p.x > z.x - 10 && p.row === z.row && z.ready) {
                        p.attack()
                        z.attacking()
                    }
                }

            }
        }
    }

    updateShroom() {
        for (let p of this.shrooms) {
            p.sleep()
            for (let z of this.zombies) {
                if (z.row == p.row && z.ready) {
                    p.awake()
                }
            }
        }
    }

    updateGarlic() {
        for (let p of this.garlics) {
            for (let z of this.zombies) {
                if (p.x < z.x && p.x > z.x - 10 && z.row == p.row && z.ready) {
                    p.attack()
                    log('Gralicd dsfsdf', z.y, z.row)
                    z.Gralicd()
                    log('Gralicd', z.y, z.row)
                }
            }
        }
    }

    updateSpikeweed() {
        for (let p of this.spikeweeds) {
            for (let z of this.zombies) {
                if (p.x < z.x && p.x > z.x - 10 && z.row == p.row && z.ready) {
                    z.spiked()
                    // log('z.speed', z.zombie_speed, z.hp)
                }
            }
        }
    }

    updateIceshroom() {
        for (let p of this.iceshrooms) {
            for (let z of this.zombies) {
                if (z.ready) {
                    // p.remove()
                    if (p.ready) {
                        z.iced()
                        log('z.zombie_speed', z.zombie_speed)
                        p.remove()
                    }
                }
            }
        }
    }

    updateOther() {
        for (let p of this.others) {
            for (let z of this.zombies) {
                if (p.x < z.x && p.x > z.x - 10 && p.row === z.row && z.ready) {
                    log('updateOther', p.row, z.row)
                    //&& p.column ===z.column
                    p.cracked()
                    z.attacking()
                }
            }
        }
    }

    updateChomper() {
        for (let p of this.chomper) {
            for (let z of this.zombies) {
                if (p.x < z.x && p.x > z.x - 10 && p.row === z.row && z.ready) {
                    log('updateOther', p.row, z.row)
                    //&& p.column ===z.column
                    p.cracked()
                    z.remove()
                }
            }
        }
    }


    updatehypnoshroom() {
        for (let p of this.hypnoshroom) {
            for (let z of this.zombies) {
                if (p.x < z.x && p.x > z.x - 10 && p.row === z.row && z.ready) {
                    log('updateOther', p.row, z.row)
                    //&& p.column ===z.column
                    p.awake()
                    z.attack()
                }
            }
        }
    }

    updateScore() {
        this.score += 25
    }

    updateFire() {
        for (let p of this.peas) {
            p.sleep()
            for (let z of this.zombies) {
                if (z.row == p.row && z.ready) {
                    p.awake()
                }
            }
        }
    }

    updateLawnMower() {
        for (let p of this.pawnMower) {
            if (p.x > this.width) {
                p.remove()
            }
            for (let z of this.zombies) {
                if (p.row === z.row) {
                    if (p.x + 2 > z.x && p.x - 2 > z.x) {
                        log('撞到了')
                        p.ready = true
                        z.die()
                    }
                }
            }
        }
    }

    updateHit() {
        // let bullets = this.e
        for (let z of this.zombies) {
            let row = z.row
            for (let b of this.bullets) {
                if (b.row == row && z.ready) {
                    // 判断是否相撞
                    if (z.x - b.x < this.bulletHitOffset) {
                        z.beattack(b.damage)
                        // this.numOfZombie = this.zombies.length - 1
                        b.remove()
                    }
                }
            }
        }
    }

    updatePrepare() {
        this.slogan.prepare--
        this.sloganlarge--
        this.sloganfinal--
        this.slogan.x += 1
        if (this.slogan.prepare === 0) {
            this.slogan.remove()
        }
        // if (this.sloganlarge === 0) {
        //     this.addSlogan('slogan_large')
        // }

        // if (this.sloganfinal === 0) {
        //     this.addSlogan('slogan_final')
        // }

    }

    updateScene() {
        for (let z of this.zombies) {
            if (z.x < 100) {
                sleep(500).then(() => {
                    let s = SceneLooseEnd.new(this.game)
                    this.game.replaceScene(s)
                })
                this.game.removeMouse()
            }
        }
        if (this.zombies.length === 0) {
            log('游戏胜利')
            sleep(0).then(() => {
                let s = SceneVictoryeEnd.new(this.game)
                this.game.replaceScene(s)
                // this.game.runWithScene(s)
            })
            this.game.removeMouse()
        }
    }

    debug() {
        this.bulletHitOffset = config.hit_offset.value
    }

}